/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.service.impl;

import com.minierp.bean.SetuBillBean;
import com.minierp.bean.SetuBillItemBean;
import com.minierp.bean.UserBean;
import com.minierp.dao.BusinessBillItemDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.SerialNumberDao;
import com.minierp.dao.SetuBillDao;
import com.minierp.dao.SetuBillItemDao;
import com.minierp.err.DataChangedException;
import com.minierp.err.NotAllowException;
import com.minierp.helper.PageHelper;
import com.minierp.model.BusinessBill;
import com.minierp.model.BusinessBillExt;
import com.minierp.model.BusinessBillItem;
import com.minierp.model.BusinessBillItemExt;
import com.minierp.model.SetuBill;
import com.minierp.model.SetuBillItem;
import com.minierp.model.SetuDetail;
import com.minierp.model.SystemLog;
import com.minierp.service.SetuBillService;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

public class SetuBillServiceImpl implements SetuBillService {
	public void txInsert(SetuBillBean form, UserBean ub,
			SetuBillDao setuBillDao, SetuBillItemDao setuBillItemDao,
			BusinessBillItemDao businessBillItemDao,
			SerialNumberDao serialNumberDao, IdGenerator idGenerator)
			throws Exception {
		SetuBill obj = form.getSetuBill();
		obj.setCreaTime(new Date());
		obj.setId(idGenerator.getId(SetuBill.class.getName()));
		if (!form.getCodeRule().getGenerateRule().equals("MANUAL")) {
			obj.setBillCode(PageHelper.generateCode(serialNumberDao,
					form.getCodeRule(), "", form.getSetuBill().getTsId()));

			for (SetuBill deliList = setuBillDao.get(obj.getBillCode()); deliList != null; deliList = setuBillDao
					.get(obj.getBillCode())) {
				obj.setBillCode(PageHelper.generateCode(serialNumberDao,
						form.getCodeRule(), "", form.getSetuBill().getTsId()));
			}
		}

		List arg11 = setuBillDao.getListByBusinessBill(obj.getBbId());

		for (int j = 0; j < arg11.size(); ++j) {
			SetuBill rb = (SetuBill) arg11.get(j);
			if (rb.getExam().equals("N")) {
				throw new NotAllowException(
						"该业务单存在未审核的安装单，安装单号为"
								+ rb.getBillCode()
								+ "，请进入【客户业务-安装单一览表】找到这张安装单，把这张之前开过的未审核安装单审核通过就可以了，不需要再开安装单。");
			}
		}

		if (obj.getExam().equals("Y")) {
			obj.setExamTime(new Date());
		}

		setuBillDao.save(obj);
		this.saveItems(form, ub, setuBillItemDao, businessBillItemDao,
				idGenerator);
	}

	public void txUpdate(SetuBillBean form, UserBean ub,
			SetuBillDao setuBillDao, SetuBillItemDao setuBillItemDao,
			BusinessBillItemDao businessBillItemDao, IdGenerator idGenerator)
			throws Exception {
		SetuBill obj = form.getSetuBill();
		Object[] sv = setuBillDao.getStatusValues(obj.getId());
		if (sv == null) {
			throw new Exception("Can\'t get status values for setu bill:"
					+ obj.getId());
		} else {
			long existSycVal = ((Date) sv[0]).getTime();
			String exitEnabled = sv[1].toString();
			String existExamined = sv[2].toString();
			if (existSycVal != form.getSychronizeValue()) {
				throw new DataChangedException("安装单已被其他操作修改，请关闭页面再打开后重新操作！");
			} else if (exitEnabled.equals("N")) {
				throw new NotAllowException("安装单已作废，不能修改！");
			} else if (existExamined.equals("Y")) {
				throw new NotAllowException("安装单已审核，不能修改！");
			} else {
				if (obj.getExam().equals("Y")) {
					obj.setExamTime(new Date());
				}

				obj.setUpdaTime(new Date());
				setuBillDao.update(obj);
				this.saveItems(form, ub, setuBillItemDao, businessBillItemDao,
						idGenerator);
			}
		}
	}

	private void saveItems(SetuBillBean form, BusinessBill b,
			BusinessBillExt be, UserBean ub, List bbItemList,
			SetuBillItemDao setuBillItemDao, IdGenerator idGenerator)
			throws NotAllowException {
		List items = form.getItems();
		String errorMsg = "";
		if (b == null) {
			errorMsg = "找不到id为" + form.getSetuBill().getBbId() + "的业务单";
		} else if (be.getExamined().equals("N")) {
			errorMsg = "业务单还没审核，不能安装。单号：" + b.getBillCode();
		} else if (be.getEnabled().equals("N")) {
			errorMsg = "业务单已作废，不能安装。单号：" + b.getBillCode();
		} else if (be.getClosed().equals("Y")) {
			errorMsg = "业务单已结清，不能安装。单号：" + b.getBillCode();
		}

		if (!errorMsg.equals("")) {
			throw new NotAllowException(errorMsg);
		} else {
			int newNum = 0;

			for (int curItemId = 0; curItemId < items.size(); ++curItemId) {
				SetuBillItemBean bean = (SetuBillItemBean) items.get(curItemId);
				if (bean.getOldId() == 0L
						&& bean.getSetuBillItem().getAmount()
								.compareTo(new BigDecimal(0)) != 0) {
					++newNum;
				}
			}

			long arg22 = 0L;
			if (newNum > 0) {
				arg22 = idGenerator.getId(SetuBillItem.class.getName(), newNum);
			}

			for (int setuped = 0; setuped < items.size(); ++setuped) {
				SetuBillItemBean hasItemSetu = (SetuBillItemBean) items
						.get(setuped);
				long j = hasItemSetu.getSetuBillItem().getBbItemId();
				hasItemSetu.getSetuBillItem().setBillId(
						form.getSetuBill().getId());
				boolean bbItem = false;
				if (hasItemSetu.getOldId() != 0L) {
					if (hasItemSetu.getSetuBillItem().getAmount()
							.compareTo(new BigDecimal(0)) == 0) {
						setuBillItemDao.delete(hasItemSetu.getSetuBillItem()
								.getId());
					} else {
						setuBillItemDao.update(hasItemSetu.getSetuBillItem());
						bbItem = true;
					}
				} else if (hasItemSetu.getSetuBillItem().getAmount()
						.compareTo(new BigDecimal(0)) != 0) {
					hasItemSetu.getSetuBillItem().setId(arg22);
					setuBillItemDao.save(hasItemSetu.getSetuBillItem());
					++arg22;
					bbItem = true;
				}

				BusinessBillItem bbIe = null;
				BusinessBillItemExt bbIe1 = null;
				boolean foundBbItem = false;

				for (int setuAmount = 0; setuAmount < bbItemList.size(); ++setuAmount) {
					Object[] objs1 = (Object[]) bbItemList.get(setuAmount);
					bbIe = (BusinessBillItem) objs1[0];
					bbIe1 = (BusinessBillItemExt) objs1[1];
					if (bbIe.getId() == j) {
						foundBbItem = true;
						break;
					}
				}

				if (foundBbItem) {
					if (bbItem) {
						BigDecimal arg28 = setuBillItemDao.getSetuAmount(j);
						if (arg28.compareTo(bbIe.getAmount()) == 1) {
							throw new NotAllowException("安装数量不能超过订货数量，请修正！");
						}
					}

					if (form.getSetuBill().getExam().equals("Y") && bbItem) {
						bbIe1.setSetuAmou(bbIe1.getSetuAmou().add(
								hasItemSetu.getSetuBillItem().getAmount()));
						setuBillItemDao.update(bbIe1);
					}
				}
			}

			String arg23 = "Y";
			String arg24 = "N";

			for (int arg25 = 0; arg25 < bbItemList.size(); ++arg25) {
				Object[] objs = (Object[]) bbItemList.get(arg25);
				BusinessBillItem arg26 = (BusinessBillItem) objs[0];
				BusinessBillItemExt arg27 = (BusinessBillItemExt) objs[1];
				if (arg26.getIsSetu().equals("Y")) {
					if (arg27.getSetuAmou().compareTo(new BigDecimal(0)) == 0) {
						arg23 = "N";
						if (arg24.equals("Y")) {
							arg23 = "P";
							break;
						}
					} else {
						if (arg27.getSetuAmou().compareTo(arg26.getAmount()) != 0) {
							arg23 = "P";
							break;
						}

						arg24 = "Y";
					}
				}
			}

			be.setSetuped(arg23);
			be.setHasSetu("Y");
			setuBillItemDao.update(be);
		}
	}

	private void saveItems(SetuBillBean form, UserBean ub,
			SetuBillItemDao setuBillItemDao,
			BusinessBillItemDao businessBillItemDao, IdGenerator idGenerator)
			throws NotAllowException {
		BusinessBill b = (BusinessBill) businessBillItemDao.get(
				BusinessBill.class, form.getSetuBill().getBbId());
		BusinessBillExt be = (BusinessBillExt) businessBillItemDao.get(
				BusinessBillExt.class, form.getSetuBill().getBbId());
		List bbItemList = businessBillItemDao.getListWidthExt(b.getId());
		this.saveItems(form, b, be, ub, bbItemList, setuBillItemDao,
				idGenerator);
	}

	public void txExamine(long id, UserBean ub, SetuBillDao setuBillDao,
			SetuBillItemDao setuBillItemDao,
			BusinessBillItemDao businessBillItemDao) throws Exception {
		SetuBill a = (SetuBill) setuBillDao.get(SetuBill.class, id);
		if (a != null && a.getEnab().equals("Y") && a.getExam().equals("N")) {
			List itemList = setuBillItemDao.getListBySetuBill(a.getId());
			a.setExam("Y");
			a.setExamTime(new Date());
			a.setExamId(ub.getStaffer().getId());
			a.setExamName(ub.getStaffer().getStafferName());
			a.setUpdaTime(new Date());
			setuBillDao.update(a);
			this.updateBusinessBill(itemList, ub, a.getBbId(), true, false,
					businessBillItemDao, setuBillDao);
		}

	}

	private void updateBusinessBill(List<?> itemList, UserBean ub, long bbId,
			boolean isAdd, boolean checkHasSetu,
			BusinessBillItemDao businessBillItemDao, SetuBillDao setuBillDao)
			throws NotAllowException {
		BusinessBill b = (BusinessBill) businessBillItemDao.get(
				BusinessBill.class, bbId);
		BusinessBillExt be = (BusinessBillExt) businessBillItemDao.get(
				BusinessBillExt.class, bbId);
		String errorMsg = "";
		if (b == null) {
			errorMsg = "找不到id为" + bbId + "的业务单";
		} else if (be.getExamined().equals("N")) {
			errorMsg = "单号为" + b.getBillCode() + "的业务单还没审核，不能操作";
		} else if (be.getEnabled().equals("N")) {
			errorMsg = "单号为" + b.getBillCode() + "的业务单已作废，不能操作";
		} else if (be.getClosed().equals("Y")) {
			errorMsg = "单号为" + b.getBillCode() + "的业务单已结清，不能操作";
		}

		if (!errorMsg.equals("")) {
			throw new NotAllowException(errorMsg);
		} else {
			List bbItemList = businessBillItemDao.getListWidthExt(b.getId());

			for (int setuped = 0; setuped < itemList.size(); ++setuped) {
				SetuBillItem hasItemSetu = (SetuBillItem) itemList.get(setuped);
				BigDecimal j;
				if (isAdd) {
					j = hasItemSetu.getAmount();
				} else {
					j = (new BigDecimal(0)).subtract(hasItemSetu.getAmount());
				}

				for (int objs = 0; objs < bbItemList.size(); ++objs) {
					Object[] bbItem = (Object[]) bbItemList.get(objs);
					BusinessBillItem bbIe = (BusinessBillItem) bbItem[0];
					BusinessBillItemExt bbIe1 = (BusinessBillItemExt) bbItem[1];
					if (bbIe.getId() == hasItemSetu.getBbItemId()) {
						bbIe1.setSetuAmou(bbIe1.getSetuAmou().add(j));
						businessBillItemDao.update(bbIe1);
						break;
					}
				}
			}

			if (checkHasSetu) {
				List arg19 = setuBillDao.getListByBusinessBill(b.getId());
				if (arg19.size() > 0) {
					be.setHasSetu("Y");
				} else {
					be.setHasSetu("N");
				}
			}

			String arg20 = "Y";
			String arg21 = "N";

			for (int arg22 = 0; arg22 < bbItemList.size(); ++arg22) {
				Object[] arg23 = (Object[]) bbItemList.get(arg22);
				BusinessBillItem arg24 = (BusinessBillItem) arg23[0];
				BusinessBillItemExt arg25 = (BusinessBillItemExt) arg23[1];
				if (arg24.getIsSetu().equals("Y")) {
					if (arg25.getSetuAmou().compareTo(new BigDecimal(0)) == 0) {
						arg20 = "N";
						if (arg21.equals("Y")) {
							arg20 = "P";
							break;
						}
					} else {
						if (arg25.getSetuAmou().compareTo(arg24.getAmount()) != 0) {
							arg20 = "P";
							break;
						}

						arg21 = "Y";
					}
				}
			}

			be.setSetuped(arg20);
			businessBillItemDao.update(be);
		}
	}

	public void txUnExamine(long id, UserBean ub, SetuBillDao setuBillDao,
			SetuBillItemDao setuBillItemDao,
			BusinessBillItemDao businessBillItemDao) throws Exception {
		SetuBill a = (SetuBill) setuBillDao.get(SetuBill.class, id);
		if (a.getComp().equals("Y")) {
			throw new NotAllowException("安装单已经完工，不能反审核！");
		} else {
			if (a != null && a.getEnab().equals("Y") && a.getExam().equals("Y")) {
				a.setExam("N");
				a.setExamId(0L);
				a.setExamName("");
				a.setUpdaTime(new Date());
				setuBillDao.update(a);
				List itemList = setuBillItemDao.getListBySetuBill(a.getId());
				this.updateBusinessBill(itemList, ub, a.getBbId(), false,
						false, businessBillItemDao, setuBillDao);
			}

		}
	}

	public void txCancel(long id, String reason, UserBean ub,
			SetuBillDao setuBillDao, SetuBillItemDao setuBillItemDao,
			BusinessBillItemDao businessBillItemDao, IdGenerator idGenerator)
			throws Exception {
		SetuBill d = (SetuBill) setuBillDao.get(SetuBill.class, id);
		if (d != null && d.getEnab().equals("Y")) {
			d.setEnab("N");
			d.setDisaId(ub.getUser().getStafferId());
			d.setUpdaTime(new Date());
			setuBillDao.update(d);
			if (d.getExam().equals("Y")) {
				List log = setuBillItemDao.getListBySetuBill(d.getId());
				this.updateBusinessBill(log, ub, d.getBbId(), false, true,
						businessBillItemDao, setuBillDao);
			} else {
				BusinessBillExt log1 = (BusinessBillExt) setuBillDao.get(
						BusinessBillExt.class, d.getBbId());
				String errorMsg = "";
				if (log1 == null) {
					errorMsg = "找不到id为" + d.getBbId() + "的业务单";
				}

				if (!errorMsg.equals("")) {
					throw new NotAllowException(errorMsg);
				}

				List iList = setuBillDao.getListByBusinessBill(d.getBbId());
				if (iList.size() > 0) {
					log1.setHasSetu("Y");
				} else {
					log1.setHasSetu("N");
				}

				setuBillDao.update(log1);
			}

			SystemLog log2 = new SystemLog();
			log2.setId(idGenerator.getId(SystemLog.class.getName()));
			log2.setActionCode("SETU_BILL");
			log2.setLogType("CANCEL_LOG");
			log2.setCreaterId(ub.getStaffer().getId());
			log2.setCreaterName(ub.getStaffer().getStafferName());
			log2.setDepName(ub.getDepName());
			log2.setDepId(ub.getStaffer().getDepartmentId());
			log2.setStatus("S");
			log2.setUserName(ub.getUser().getUserName());
			log2.setIp(d.getBillCode());
			log2.setMark("");
			log2.setRelId(id);
			log2.setCancelReason(reason);
			log2.setTallySetId(d.getTsId());
			setuBillDao.save(log2);
		}

	}

	public void txComp(long id, Date realDate, String setuIdStr,
			String setuNameStr, BigDecimal cost, String compImg, UserBean ub,
			SetuBillDao setuBillDao, IdGenerator idGenerator) throws Exception {
		SetuBill d = (SetuBill) setuBillDao.get(SetuBill.class, id);
		if (d != null && d.getEnab().equals("Y")) {
			if (d.getExam().equals("N")) {
				throw new NotAllowException("安装单未审核，要完工请先审核！");
			} else if (d.getComp().equals("Y")) {
				throw new NotAllowException("安装单已经完工，要重新完工请先反完工！");
			} else {
				d.setRealDate(realDate);
				d.setSetuIdStr(setuIdStr);
				d.setSetuNameStr(setuNameStr);
				d.setCost(cost);
				d.setCompImg(compImg);
				d.setComp("Y");
				d.setCompId(ub.getStaffer().getId());
				d.setCompName(ub.getStaffer().getStafferName());
				d.setCompTime(new Date());
				setuBillDao.update(d);
				this.insertSetuDetail(id, setuIdStr, setuBillDao, idGenerator);
			}
		} else {
			throw new NotAllowException("找不到对应单据：单据已作废！");
		}
	}

	public void txUnComp(long id, SetuBillDao setuBillDao) throws Exception {
		SetuBill d = (SetuBill) setuBillDao.get(SetuBill.class, id);
		if (d != null && d.getEnab().equals("Y") && d.getExam().equals("Y")
				&& d.getComp().equals("Y")) {
			d.setRealDate((Date) null);
			d.setComp("N");
			d.setCompId(0L);
			d.setCompName("");
			d.setCompTime((Date) null);
			setuBillDao.update(d);
			setuBillDao.clearSetuDetail(d.getId());
		}

	}

	private void insertSetuDetail(long billId, String setuIdStr,
			SetuBillDao setuBillDao, IdGenerator idGenerator) {
		if (setuIdStr != null && !setuIdStr.equals("")) {
			String[] arr = setuIdStr.split(";");
			long curId = idGenerator.getId(SetuDetail.class.getName(),
					arr.length);

			for (int i = 0; i < arr.length; ++i) {
				if (arr[i] != null && !arr[i].equals("")) {
					String[] tmpArr = arr[i].split(":");
					SetuDetail dd = new SetuDetail();
					dd.setId(curId);
					dd.setBillId(billId);
					dd.setPercent(new BigDecimal(tmpArr[1]));
					dd.setStafferId(Long.parseLong(tmpArr[0]));
					setuBillDao.save(dd);
					++curId;
				}
			}
		}

	}
}